package com.zsrt.devbase.common.utils;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Shiro权限框架，工具类
 *
 */
public final class ShiroUtil {
	
	private static Logger logger = Logger.getLogger(ShiroUtil.class);
	/**
	 * 设置session
	 * @param key
	 * @param value
	 */
	public static void setSession(String key,Object value){
		Subject subject = SecurityUtils.getSubject();
		if(null == subject){
			return;
		}
		Session session = subject.getSession(true);
		if(null != session){
			session.setAttribute(key, value);
		}
	}
	
	/**
	 * 根据key，从session中取得具体的对象
	 * @param key
	 * @param value
	 */
	public static Object getSessionByKey(String key){
		Session session = SecurityUtils.getSubject().getSession(false);
		if(null != session){
			return session.getAttribute(key);
		}
		return null;
	}
	
	/**
	 * 根据key，从session中删除具体的对象
	 * @param key
	 * @return
	 */
	public static void removeSessionByKey(String key){
		Session session = SecurityUtils.getSubject().getSession(false);
		if(null != session){
			session.removeAttribute(key);
		}		
	}
	
	/**
	 * 设置session
	 * @param key
	 * @param value
	 * @param timeOut  分钟数
	 */
	public static void setSession(String key,Object value,String timeOut){
		Session session = SecurityUtils.getSubject().getSession(false);
		try {
			if(null != session){
				int longTimeOut=Integer.parseInt(timeOut)*1000*60;
				session.setTimeout(longTimeOut);
				session.setAttribute(key, value);
				
			}
		} catch (InvalidSessionException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
	}
}
